const http = require('http')
const path = require('path')
const fs = require('fs')
const server = http.createServer((req,res)=>{
    let filePath = path.resolve(__dirname,'www',req.url=='/'?"index.html":req.url)
    if(fs.existsSync(filePath)){
        const stats = fs.statSync(filePath)
        if(stats.isDirectory()){
            filePath = path.join(filePath,"index.html")
            if(!fs.existsSync(filePath)){
                res.writeHead(404,{'content-type': 'text/plain'})
                return res.end("Not Found")
            }
        }

        const ext = path.extname(filePath).toLowerCase()
        
        const fileStates = fs.statSync(filePath)
        const lastModified = new Date(fileStates.mtimeMs).toUTCString();
        const ifModifinedSince = req.headers['if-modified-since']
        if(ifModifinedSince){
            const clientTime = new Date(ifModifinedSince).getTime();
            const serverTime = fileStates.mtimeMs
             if (Math.floor(clientTime / 1000) >= Math.floor(serverTime / 1000)) { //如果相同则设置304，不返回东西
                res.writeHead(304, {
                    'last-modified': lastModified, 
                });
             console.log('304 Sent');
             return res.end();
                }
        }
        res.writeHead(200,{
            'content-type':"text/html",
            'last-modified': lastModified
        }) 
         const readStream = fs.createReadStream(filePath);
         readStream.pipe(res)
         console.log('200 Sent');
    }else{
        res.writeHead(404,{'content-type':"text/plain"})
        res.end('Not Found')
    }
})
server.listen(3000,()=>{
    console.log("哥们，端口我给你开了，我们来交流一下吧");
})